package com.example.cofeed.activity.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ada.common.cache.CacheManager;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.example.cofeed.R;
import com.example.cofeed.activity.LoginActivity;
import com.example.cofeed.adapter.PagerAdapter;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseFragment;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.entity.Navigator;
import com.example.cofeed.even.LoginEeven;
import com.example.cofeed.widget.ChannelView;
import com.flyco.tablayout.SlidingTabLayout;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class DemandSubTabFragment extends BaseFragment implements ChannelView.OnChannelListener{
    @BindView(R.id.tabs)
    SlidingTabLayout mTabs;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private int mType;
    private int mPosition;
    private List<Navigator> mNavigators = new ArrayList<>();
    private List<Navigator> catdata;

    public static DemandSubTabFragment newInstance(int type) {
        DemandSubTabFragment fragment = new DemandSubTabFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(IntentKeyConstant.TYPE, type);
        fragment.setArguments(bundle);
        return fragment;

    }

    @Override
    protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_demand_sub_tab, container, false);
        return view;
    }

    @Override
    protected void initData() {

        if (getArguments() != null) {
            mType = getArguments().getInt(IntentKeyConstant.TYPE);
        }

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                mPosition = i;

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        ApiService.navigator_supply_nav(this, new DialogCallback<LzyResponse<List<Navigator>>>(getActivity()) {
            @Override
            public void onSuccess(Response<LzyResponse<List<Navigator>>> response) {
                mNavigators.clear();
                mNavigators.addAll(response.body().data);
                List<String> titles = new ArrayList<>();
                for (Navigator navigator : response.body().data) {
                    mFragments.add(DemandListFragment.newInstance(mType, navigator.catid));
                    titles.add(navigator.title);
                }

                Navigator tuijian = new Navigator();
                tuijian.title = "全部";
                mNavigators.add(0, tuijian);

                mFragments.add(0, DemandListFragment.newInstance(0, 0));
                titles.add(0, "全部");

                mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), mFragments, titles));
                mTabs.setViewPager(mViewPager);
                mViewPager.setOffscreenPageLimit(titles.size() - 1);

                mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int i, float v, int i1) {

                    }

                    @Override
                    public void onPageSelected(int i) {
                        DemandListFragment homelistFragment = (DemandListFragment) mFragments.get(i);
                        homelistFragment.updateArguments(mType, mNavigators.get(i).catid);


                    }

                    @Override
                    public void onPageScrollStateChanged(int i) {

                    }
                });


                for (int i = 0; i < titles.size(); i++) {
                    TextView textView = mTabs.getTitleView(i);
                    String title = titles.get(i);
                    switch (title.length()){
                        case 4:
                            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                            break;
                        case 5:
                            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                            break;
                        case 6:
                            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                            break;
                        default:
                            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                            break;
                    }

                }

            }
        });
    }

    public int getcatId() {
        return mNavigators.get(mPosition).catid;
    }

    @OnClick(R.id.iv_menu)
    public void onViewClicked() {
        if (ObjectUtils.isEmpty(mNavigators)){
            return;
        }

        showMenuDialog();

    }

    Dialog mDialog;
    ChannelView mChannelView;
    private void showMenuDialog() {
//        if (mDialog == null){
        mDialog = new Dialog(getActivity());
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_channel, null, false);
        mChannelView = inflate.findViewById(R.id.channelView);
//            if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))){
//                mChannelView.setEditTxt("未登录");
//            }
        inflate.findViewById(R.id.iv_close).setOnClickListener(v->{
            if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))){
                mDialog.dismiss();
                return;
            }
            mChannelView.getMyChannel();
            ArrayList<Navigator> navigators = new ArrayList<>();
            ArrayList<Navigator> orcNavigators = new ArrayList<>();
            orcNavigators.addAll(mNavigators);
            orcNavigators.remove(0);

            for (String s:mChannelView.getMyChannel()){
                if (s.contains("x")){
                    s = s.replace("x", "").trim();
                }
                s = s.replace(" ", "");

                boolean isExit = false;
                for (Navigator navigator:orcNavigators){
                    if (navigator.title.equals(s)){
                        navigators.add(navigator);
                        isExit = true;
                        break;
                    }
                }
                if (!isExit){
                    for (Navigator navigator:catdata){
                        if (navigator.title.equals(s)){
                            navigators.add(navigator);
                            isExit = true;
                            break;
                        }
                    }
                }

            }

            ApiService.navigator_save_supply_custom(this, navigators, new DialogCallback<LzyResponse<Object>>() {
                @Override
                public void onSuccess(Response<LzyResponse<Object>> response) {
                    CacheManager.putObject(SputilsConstant.NAVIGATOR, navigators);
                    mDialog.dismiss();

                    ApiService.navigator_supply_nav(this, new DialogCallback<LzyResponse<List<Navigator>>>(getActivity()) {
                        @Override
                        public void onSuccess(Response<LzyResponse<List<Navigator>>> response) {
                            mNavigators.clear();
                            mFragments.clear();
                            mFragments = null;
                            mFragments = new ArrayList<>();
                            mNavigators.addAll(response.body().data);
                            List<String> titles = new ArrayList<>();
                            for (Navigator navigator : response.body().data) {
                                mFragments.add(DemandListFragment.newInstance(mType, navigator.catid));
                                titles.add(navigator.title);
                            }

                            Navigator tuijian = new Navigator();
                            tuijian.title = "全部";
                            mNavigators.add(0, tuijian);

                            mFragments.add(0, DemandListFragment.newInstance(0, 0));
                            titles.add(0, "全部");

                            mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), mFragments, titles));
                            mTabs.setViewPager(mViewPager);
                            mViewPager.setOffscreenPageLimit(titles.size() - 1);

                        }
                    });

                }
            });

        });
        mDialog.setContentView(inflate);
//        }

        ApiService.navigator_supply(this, new DialogCallback<LzyResponse<List<Navigator>>>(getActivity()) {
            @Override
            public void onSuccess(Response<LzyResponse<List<Navigator>>> response) {
                catdata = response.body().data;
//                chdata = response.body().data.chdata;
                String[] myChannel = new String[mNavigators.size()];
                for (int i = 0; i < mNavigators.size(); i++) {
                    myChannel[i] = mNavigators.get(i).title;

//                    if (ObjectUtils.isNotEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))){

                        for (Iterator<Navigator> it = response.body().data.iterator(); it.hasNext();) {
                            Navigator navigator = it.next();
                            if (mNavigators.get(i).title.equals(navigator.title)){
                                it.remove();
                                break;
                            }
                        }

//                    }
                }
                String[] recommendChannel0 =  new String[response.body().data.size()];
                for (int i = 0; i < response.body().data.size(); i++) {
                    recommendChannel0[i] = response.body().data.get(i).title;
                }
//                String[] recommendChannel =  new String[response.body().data.chdata.size()];
//                for (int i = 0; i < response.body().data.chdata.size(); i++) {
//                    recommendChannel[i] = response.body().data.chdata.get(i).title;
//                }

                Map<String, String[]> channels = new LinkedHashMap<>();
                channels.put("我的栏目", myChannel);
//                if (ObjectUtils.isNotEmpty(recommendChannel0)){
                    channels.put("更多品种导航", recommendChannel0);
//                }
//                channels.put("频道导航", recommendChannel);

                mChannelView.setFixedChannel(0);
//                mChannelView.setFixedChannel(1);
                mChannelView.setChannels(channels);
//                mChannelView.setChannelNormalBackground(R.drawable.bg_channel_normal);
//                mChannelView.setChannelSelectedBackground(R.drawable.bg_channel_selected);
//                mChannelView.setChannelFocusedBackground(R.drawable.bg_channel_focused);
                mChannelView.setOnChannelItemClickListener(DemandSubTabFragment.this);

            }
        });

//        ApiService.navigator_get_all(this, new DialogCallback<LzyResponse<Navigator>>(getActivity()) {
//            @Override
//            public void onSuccess(Response<LzyResponse<Navigator>> response) {
//                catdata = response.body().data.catdata;
//                chdata = response.body().data.chdata;
//                String[] myChannel = new String[mNavigators.size()];
//                for (int i = 0; i < mNavigators.size(); i++) {
//                    myChannel[i] = mNavigators.get(i).title;
//                }
//                String[] recommendChannel0 =  new String[response.body().data.catdata.size()];
//                for (int i = 0; i < response.body().data.catdata.size(); i++) {
//                    recommendChannel0[i] = response.body().data.catdata.get(i).title;
//                }
//                String[] recommendChannel =  new String[response.body().data.chdata.size()];
//                for (int i = 0; i < response.body().data.chdata.size(); i++) {
//                    recommendChannel[i] = response.body().data.chdata.get(i).title;
//                }
//
//                Map<String, String[]> channels = new LinkedHashMap<>();
//                channels.put("我的栏目", myChannel);
//                channels.put("品种导航", recommendChannel0);
//                channels.put("频道导航", recommendChannel);
//
//                mChannelView.setFixedChannel(0);
//                mChannelView.setFixedChannel(1);
//                mChannelView.setChannels(channels);
////                mChannelView.setChannelNormalBackground(R.drawable.bg_channel_normal);
////                mChannelView.setChannelSelectedBackground(R.drawable.bg_channel_selected);
////                mChannelView.setChannelFocusedBackground(R.drawable.bg_channel_focused);
//                mChannelView.setOnChannelItemClickListener(DemandSubTabFragment.this);
//
//
//            }
//        });

//        init();

        Window localWindow = mDialog.getWindow();
        localWindow.setBackgroundDrawableResource(android.R.color.transparent);
        localWindow.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
            mDialog.setCanceledOnTouchOutside(true);
            mDialog.setCancelable(true);
        }

    }

//    private void initDaohang(){
//        List<String> titles = new ArrayList<>();
//        mFragments.clear();
//        for (Navigator navigator:mNavigators){
//            mFragments.add(HomeListFragment.newInstance(navigator.catid, navigator.chid));
//            titles.add(navigator.title);
//        }
////        if (ObjectUtils.isNotEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))){
////            Navigator guanzhu = new Navigator();
////            guanzhu.title = "关注";
////            mNavigators.add(1, guanzhu);
////
////            mFragments.add(1, HomeListFragment.newInstance(-2, -2));
////            titles.add(1, "关注");
////        }
//
//        mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), mFragments, titles));
//        mTabs.setViewPager(mViewPager);
//        mViewPager.setOffscreenPageLimit(titles.size() - 1);
//
//    }

    @Override
    public void channelItemClick(int itemId, String channelItem) {
        Log.i("channel", itemId + ".." + channelItem);

        if (mDialog != null) {

            boolean isExitItem = false;
            for (int i = 0; i < mNavigators.size(); i++) {
                if (channelItem.equals(mNavigators.get(i).title)) {
                    mViewPager.setCurrentItem(i);
                    isExitItem = true;
                    break;
                }
            }

            if (!isExitItem) {
                ArrayList<Navigator> navigators = new ArrayList<>();
                navigators.addAll(mNavigators);
                navigators.remove(0);
                navigators.remove(0);

                String s = channelItem;
                boolean isExit = false;
                for (Navigator navigator : mNavigators) {
                    if (navigator.title.equals(s)) {
                        navigators.add(navigator);
                        isExit = true;
                        break;
                    }
                }
                if (!isExit) {
                    for (Navigator navigator : catdata) {
                        if (navigator.title.equals(s)) {
                            navigators.add(navigator);
                            isExit = true;
                            break;
                        }
                    }
                }
//                if (!isExit) {
//                    for (Navigator navigator : chdata) {
//                        if (navigator.title.equals(s)) {
//                            navigators.add(navigator);
//                            break;
//                        }
//                    }
//                }
//                }

                ApiService.navigator_save_supply_custom(this, navigators, new DialogCallback<LzyResponse<Object>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<Object>> response) {
                        CacheManager.putObject(SputilsConstant.NAVIGATOR, navigators);
                        mDialog.dismiss();

                        ApiService.navigator_supply_nav(this, new DialogCallback<LzyResponse<List<Navigator>>>(getActivity()) {
                            @Override
                            public void onSuccess(Response<LzyResponse<List<Navigator>>> response) {
                                mNavigators.clear();
                                mNavigators.addAll(response.body().data);
                                List<String> titles = new ArrayList<>();
                                for (Navigator navigator : response.body().data) {
                                    mFragments.add(DemandListFragment.newInstance(mType, navigator.catid));
                                    titles.add(navigator.title);
                                }

                                Navigator tuijian = new Navigator();
                                tuijian.title = "全部";
                                mNavigators.add(0, tuijian);

                                mFragments.add(0, DemandListFragment.newInstance(0, 0));
                                titles.add(0, "全部");

                                mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), mFragments, titles));
                                mTabs.setViewPager(mViewPager);
                                mViewPager.setOffscreenPageLimit(titles.size() - 1);

                                for (int i = 0; i < mNavigators.size(); i++) {
                                    if (channelItem.equals(mNavigators.get(i).title)) {
                                        mViewPager.setCurrentItem(i);
                                        break;
                                    }
                                }

                            }
                        });

                    }
                });

//                ApiService.navigator_add_custom(this, navigators, new DialogCallback<LzyResponse<Object>>() {
//                    @Override
//                    public void onSuccess(Response<LzyResponse<Object>> response) {
//                        CacheManager.putObject(SputilsConstant.NAVIGATOR, navigators);
//                        mDialog.dismiss();
//                        ApiService.navigator_index(this, new DialogCallback<LzyResponse<ArrayList<Navigator>>>(getActivity()) {
//                            @Override
//                            public void onSuccess(Response<LzyResponse<ArrayList<Navigator>>> response) {
//                                mNavigators.clear();
//                                mNavigators.addAll(response.body().data);
//
//                                initDaohang();
//
//                                for (int i = 0; i < mNavigators.size(); i++) {
//                                    if (channelItem.equals(mNavigators.get(i).title)) {
//                                        mViewPager.setCurrentItem(i);
//                                        break;
//                                    }
//                                }
//
//                                CacheManager.putObject(SputilsConstant.NAVIGATOR, mNavigators);
//
//                            }
//                        });
//
//                    }
//                });
            }

            if (!isExitItem) {
                ApiService.navigator_supply_nav(this, new DialogCallback<LzyResponse<List<Navigator>>>(getActivity()) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<Navigator>>> response) {
                        mNavigators.clear();
                        mNavigators.addAll(response.body().data);
                        List<String> titles = new ArrayList<>();
                        for (Navigator navigator : response.body().data) {
                            mFragments.add(DemandListFragment.newInstance(mType, navigator.catid));
                            titles.add(navigator.title);
                        }

                        Navigator tuijian = new Navigator();
                        tuijian.title = "全部";
                        mNavigators.add(0, tuijian);

                        mFragments.add(0, DemandListFragment.newInstance(0, 0));
                        titles.add(0, "全部");

                        mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), mFragments, titles));
                        mTabs.setViewPager(mViewPager);
                        mViewPager.setOffscreenPageLimit(titles.size() - 1);

                        for (int i = 0; i < mNavigators.size(); i++) {
                            if (channelItem.equals(mNavigators.get(i).title)) {
                                mViewPager.setCurrentItem(i);
                                break;
                            }
                        }

                    }
                });
            }

            mDialog.dismiss();

        }
    }

    @Override
    public void channelFinish(List<String> channels) {
        Log.i("channel", channels.toString());
    }

    @Override
    public void noLogin() {
        ActivityUtils.startActivity(LoginActivity.class);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Login(LoginEeven loginEeven){
        initData();
        if (mDialog != null){
            mChannelView.setEditTxt("编辑");
        }
    }

}
